#
# LPodPlaylistSourceViewItem.py
#
# This work is released under the GNU GPL, version 2 or later.
#

from LSourceViewItem import *
from LPodPlaylistDrag import *
from LTrackDrag import *
from LPodTrackDrag import *
from LMusicPodManager import *
from utils import *
#
# iPod playlist (individual)
#
class LPodPlaylistSourceViewItem(LSourceViewItem):
	def __init__(self,container,playlist):
		self.playlist = playlist
		self.name = playlist.name
		LSourceViewItem.__init__(self,container,self.name)
		self.hasContextMenu = False
		self.setDragEnabled(True)
		self.setDropEnabled(True)
		self.setRenameEnabled(0,True)
		self.playlist.connect(PYSIGNAL("renamed"),self.changedName)
	
	def changedName(self,playlist,oldName,newName):
		self.setText(0,newName)

	def makeKey(self):
		if self.playlist.master: return "A"
		else: return u'B %s'+unikode(self.name)

	def iconFileName(self):
		if self.playlist.master: return "sourcelibrary.png"
		else: return "sourceplaylist.png"

	def changeName(self,newName):
		#self.playlist.setName(newName)
		LMusicPodManager.singleton().renamePlaylist(self.playlist,newName)
		#self.buildKey()

	def buildPopup(self,mainWindow):
		pass

	def select(self,container):
		container.emit(PYSIGNAL("selectPodPlaylist"),(self.playlist,None))

	def createDrag(self,container):
		return LPodPlaylistDrag(self.playlist,container)

	def acceptDrag(self,event):
		if LTrackDrag.canDecode(event): return True
		if LPodTrackDrag.canDecode(event) and not self.playlist.master: return True
		return False
	
	def dropped(self,event):
		if LTrackDrag.canDecode(event):
			drag = LTrackDrag.decode(event)
			library = Library.mainLibrary()
			trackIDs = drag['TrackIDs']
			tracks = library.tracksWithTrackIDs(trackIDs)
			tracks = filter(lambda track: track.kind.startswith('MPEG'),tracks)
			if len(tracks)>0:
				#print "LPodPlaylistSourceViewItem.dropped accepting tracks",tracks
				LMusicPodManager.singleton().uploadTracksToPlaylist(self.playlist,tracks)
			return
		if LPodTrackDrag.canDecode(event):
			#print "LPodPlaylistSourceView:got LPodTrackDrag"
			drag = LPodTrackDrag.decode(event)
			#print "decoded to",drag
			if self.playlist.name!=drag['Playlist']: # make sure coming from different playlist
				#print "adding tracks"
				LMusicPodManager.singleton().addTrackIDsToPlaylist(self.playlist,drag['TrackIDs'])
